package com.xiaoyu.keystore;

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.cert.X509Certificate;

public class KeyStoreDemo {

	private static KeyStore getKeyStore(String keyStorePath, String password)
			throws Exception {
		// 实例化密钥库
		KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
		// 获得密钥库文件流
		FileInputStream is = new FileInputStream(keyStorePath);
		// 加载密钥库
		ks.load(is, password.toCharArray());

		is.close();

		return ks;

	}
	
	private static Signature getSignature(String keyStorePath,String password) throws Exception{
		KeyStore ks = getKeyStore(keyStorePath, password);
		X509Certificate x509Certificate = (X509Certificate) ks.getCertificate("www.zlex.org");
		Signature signature =Signature.getInstance(x509Certificate.getSigAlgName());
		return signature;
	}

	private static PrivateKey getPrivateKey(String keyStorePath, String password)
			throws Exception {
		KeyStore ks = getKeyStore(keyStorePath, password);
		// 获得private key
		PrivateKey privateKey = (PrivateKey) ks.getKey("",
				password.toCharArray());

		return privateKey;
	}

	public static void main(String[] args) {
		PrivateKey prk = null;
		try {
			prk = KeyStoreDemo.getPrivateKey(
					"/usr/local/openssl/ssl/certs/zlex.keystore", "123456");
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(prk);
		try {
			System.out.println(KeyStoreDemo.getSignature("/usr/local/openssl/ssl/certs/zlex.keystore", "123456"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}